package drazing;

/**
 * Motor de físicas
 * @author xcubo
 */
public class PhysicsEngine
{
    private CollisionDetector detector;
    private boolean on_end;

    public PhysicsEngine(ControladorCarrera rc)
    {
        detector = new CollisionDetector(rc);
        on_end = false;
    }

    /**
     * Desplaza un coche
     * @param c Coche
     * @param direction Direccion en que se desplaza
     * @param distance Velocidad de desplazamiento
     */
    public void moveCar(Car c, int direction, double speed, double timeElapsed)
    {
        double x = c.getX();
        double y = c.getY();

        //Precalculo los angulos que uso y la velocidad
        double distance = speed*timeElapsed;                        // espacio = velocidad*tiempo
        distance = distance * 3;                                    // 1 metro = 3 pixeles;
        double angle = direction*(Math.PI/32.0);
        double sin = Math.sin(angle) * distance;
        double cos = Math.cos(angle) * distance;

        //Calculo las nuevas coordenadas
        if (direction == 0)
            y -= distance;
        else if (direction == 16)
            x +=distance;
        else if (direction == 32)
            y += distance;
        else if (direction == -16)
            x -=distance;
        else
        {
            x += sin;
            y -= cos;
        }
        
        //System.out.println("Hasta ("+x+","+y+")");
        c.moveTo(x, y);
    }

    public boolean crossesLine(Car c)
    {
        boolean crossed = false;
        if (detector.hasFinished(c))
            on_end = true;
        else if (on_end)
        {
            on_end = false;
            crossed = true;
        }
        return crossed;
    }

     /**
     * Rutina de choque
     * @param c Coche que choca
     * @param tipo Tipo de choque
     */
    public void collision(Car c)
    {
        int tipo = detector.collide(c);
        int ori = c.getOrientacion();
        double sp = c.getSpeed();

        switch (tipo)
        {
            case 0:         //No collision
                break;
            case 1:         //Frontal collision
                if (c.getSpeed() > 0)
                {
                    c.setSpeed(0);
                    if (ori > 0)
                        moveCar(c,ori-32,sp/2,0.5);
                    else
                        moveCar(c,ori+32,sp/2,0.5);
                }
                break;
        }
    }

    public boolean[] offRoad(Car c)
    {
        boolean wheel[] = new boolean[4];
        for (int ind=0;ind<4;ind++)
            wheel[ind] = false;
        detector.offRoad(c, wheel);
        return wheel;
    }
}

